import 'dart:convert';

class CommunityPost {
  final int id;
  final String title;
  final String content;
  final List<String> images;
  final String authorName;
  final String authorAvatar;
  final DateTime publishTime;
  final int likeCount;
  final int commentCount;
  final int readCount;
  final List<String> tags;
  final String location;
  final bool isLiked;
  final bool isFavorited;

  CommunityPost({
    required this.id,
    required this.title,
    required this.content,
    required this.images,
    required this.authorName,
    required this.authorAvatar,
    required this.publishTime,
    required this.likeCount,
    required this.commentCount,
    required this.readCount,
    required this.tags,
    required this.location,
    this.isLiked = false,
    this.isFavorited = false,
  });

  // 静态方法：解析图片数据
  static List<String> _parseImages(dynamic imagesData) {
    if (imagesData == null) return [];
    
    if (imagesData is List) {
      List<String> imageUrls = [];
      for (var item in imagesData) {
        if (item is String) {
          // 如果是字符串，直接添加
          imageUrls.add(item);
        } else if (item is Map<String, dynamic>) {
          // 如果是对象，提取 imageUrl 字段
          String? imageUrl = item['imageUrl'];
          if (imageUrl != null && imageUrl.isNotEmpty) {
            imageUrls.add(imageUrl);
          }
        }
      }
      return imageUrls;
    } else if (imagesData is String && imagesData.isNotEmpty) {
      // 如果是字符串，按逗号分割
      return imagesData.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
    }
    
    return [];
  }

  factory CommunityPost.fromJson(Map<String, dynamic> json) {
    // 处理tags字段 - 可能是字符串或列表
    List<String> tagsList = [];
    if (json['tags'] != null) {
      if (json['tags'] is String) {
        // 如果是字符串，尝试解析JSON或按逗号分割
        String tagsStr = json['tags'];
        if (tagsStr.startsWith('[') && tagsStr.endsWith(']')) {
          // JSON格式
          try {
            tagsList = List<String>.from(jsonDecode(tagsStr));
          } catch (e) {
            tagsList = [];
          }
        } else if (tagsStr.isNotEmpty) {
          // 逗号分割格式
          tagsList = tagsStr.split(',').map((e) => e.trim()).where((e) => e.isNotEmpty).toList();
        }
      } else if (json['tags'] is List) {
        tagsList = List<String>.from(json['tags']);
      }
    }

    // 处理时间字段
    DateTime publishTime;
    if (json['createTime'] != null) {
      try {
        String timeStr = json['createTime'].toString();
        // 如果是简单格式 "yyyy-MM-dd HH:mm:ss"，需要转换为ISO格式
        if (timeStr.contains(' ') && !timeStr.contains('T')) {
          timeStr = timeStr.replaceFirst(' ', 'T');
        }
        publishTime = DateTime.parse(timeStr);
      } catch (e) {
        publishTime = DateTime.now();
      }
    } else if (json['publishTime'] != null) {
      try {
        String timeStr = json['publishTime'].toString();
        // 如果是简单格式 "yyyy-MM-dd HH:mm:ss"，需要转换为ISO格式
        if (timeStr.contains(' ') && !timeStr.contains('T')) {
          timeStr = timeStr.replaceFirst(' ', 'T');
        }
        publishTime = DateTime.parse(timeStr);
      } catch (e) {
        publishTime = DateTime.now();
      }
    } else {
      publishTime = DateTime.now();
    }

    // 处理图片字段 - 可能是字符串列表或对象列表
    List<String> imagesList = _parseImages(json['images']);

    return CommunityPost(
      id: int.tryParse(json['id'].toString()) ?? 0,
      title: json['title'] ?? '',
      content: json['content'] ?? '',
      images: imagesList,
      authorName: json['authorName'] ?? json['author_name'] ?? '匿名用户',
      authorAvatar: json['authorAvatar'] ?? json['author_avatar'] ?? '',
      publishTime: publishTime,
      likeCount: int.tryParse(json['likeCount'].toString()) ?? 0,
      commentCount: int.tryParse(json['commentCount'].toString()) ?? 0,
      readCount: int.tryParse(json['readCount'].toString()) ?? 0,
      tags: tagsList,
      location: json['location'] ?? '',
      isLiked: json['isLiked'] ?? json['is_liked'] ?? false,
      isFavorited: json['isFavorited'] ?? json['is_favorited'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
      'images': images,
      'authorName': authorName,
      'authorAvatar': authorAvatar,
      'publishTime': publishTime.toIso8601String(),
      'likeCount': likeCount,
      'commentCount': commentCount,
      'readCount': readCount,
      'tags': tags,
      'location': location,
      'isLiked': isLiked,
      'isFavorited': isFavorited,
    };
  }

  CommunityPost copyWith({
    int? id,
    String? title,
    String? content,
    List<String>? images,
    String? authorName,
    String? authorAvatar,
    DateTime? publishTime,
    int? likeCount,
    int? commentCount,
    int? readCount,
    List<String>? tags,
    String? location,
    bool? isLiked,
    bool? isFavorited,
  }) {
    return CommunityPost(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      images: images ?? this.images,
      authorName: authorName ?? this.authorName,
      authorAvatar: authorAvatar ?? this.authorAvatar,
      publishTime: publishTime ?? this.publishTime,
      likeCount: likeCount ?? this.likeCount,
      commentCount: commentCount ?? this.commentCount,
      readCount: readCount ?? this.readCount,
      tags: tags ?? this.tags,
      location: location ?? this.location,
      isLiked: isLiked ?? this.isLiked,
      isFavorited: isFavorited ?? this.isFavorited,
    );
  }
}